package com.nebula.controller.portal;

import com.alibaba.fastjson.JSON;
import com.nebula.common.Const;
import com.nebula.common.TreeResult;
import com.nebula.common.Level2Result;
import com.nebula.controller.BaseController;
import com.nebula.service.IMenuService;
import com.nebula.service.impl.MenuServiceImpl;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CcccX
 */
@WebServlet(name = "MenuController", urlPatterns = "/menu")
public class MenuController extends BaseController {

    private final IMenuService menuService = new MenuServiceImpl();

    public String levelOne(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        // 获取一级菜单
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        List<TreeResult> treeResults = menuService.selectParentNode(user.getRoleId());
        return Const.JSON + JSON.toJSONString(treeResults);
    }

    public String levelTwo(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        // 获取二级菜单
        String parentId = request.getParameter("parentId");
        if (parentId == null) {
            return null;
        }
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);

        List<Level2Result> level2Results;

        synchronized (menuService){
            level2Results = menuService.selectLevel2(user.getRoleId(), parentId);
        }

        return Const.JSON + JSON.toJSONString(level2Results);
    }

    public String levelThree(HttpServletRequest request, HttpServletResponse response) {
        // 获取三级目录
        String roleId = request.getParameter("roleId");
        if (StringUtils.isBlank(roleId)) {
            roleId = "0";
        }
        //同时加载
        ArrayList<TreeResult> treeResults = menuService.menuTree(Integer.parseInt(roleId));
        //添加系统名为根节点
        TreeResult treeResult = new TreeResult();
        treeResult.setId("0");
        treeResult.setParentId("-1");
        treeResult.setText(Const.SYSTEM_NAME);
        treeResult.setState("open");
        treeResult.setChildren(treeResults);
        treeResult.setIconCls("icon-hamburg-graphic");
        List<TreeResult> list = new ArrayList<>();
        list.add(treeResult);
        return Const.JSON + JSON.toJSONString(list);
    }

}
